﻿# Copyright (c) 2010 Yan Valuyskiy (yan.valuyskiy@gmail.com)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# v. 1.0


import launchy, os, socket
import simplejson
import urllib2
from PyGT import PyGTGui

class PyGoogleTranslate(launchy.Plugin):
	def __init__(self):
		launchy.Plugin.__init__(self)  ### 2
		self.name = "PyGoogleTranslate"  ### 3
		self.hash = launchy.hash(self.name)
		self.icon = os.path.join(launchy.getIconsPath(), "pysimple.png")
		self.__version__="1.0"
		self.__readConfig()
		
	def init(self):
		pass
		
	def getID(self):
		return self.hash

	def getName(self):
		return self.name

	def getIcon(self):
		return self.icon
		
	def getLabels(self, inputDataList):
		if len(inputDataList) < 2:
			return
		
		lowerText = inputDataList[0].getText().lower()
		if lowerText == "qe":
			inputDataList[0].setLabel( self.hash )
		
	def getResults(self, inputDataList, resultsList):
		# Take the text from the first input item and add a new
		# Catalog item with our plugin id
		text = inputDataList[0].getText()   ### 4

		if len(inputDataList) < 2:
			return

		if not inputDataList[0].hasLabel(self.hash):
			return

		text2 = inputDataList[1].getText()
		sym=text2[len(text2)-1:]
		if (sym=="." or sym=="?" or sym=="!"):
			#print " got space -> translating..."
			
			langs=self._languages[1:-1].split("|")
			for lang in langs:
				if (lang!=""):
					url=('https://www.googleapis.com/language/translate/v2?key=AIzaSyBXLEzo75SDx-ybUJhIR-yWqKgIGfPVl-Y&q=' + text2.replace(" ","%20") + '&source=&target=' + lang)
					
					request = urllib2.Request(url, None, {'Referer': os.getenv('USERNAME') + '@localPyLaunchy/host=' + socket.gethostname() })
					response = urllib2.urlopen(request)
					results = simplejson.load(response)
					
					for i in results["data"]["translations"]:
						translate_result=i["translatedText"]
						try:
							lang_det=i["detectedSourceLanguage"]
						except:
							lang_det="???"

						if (lang!=lang_det): resultsList.push_back( launchy.CatItem(lang,
							translate_result,
							self.getID(), self.getIcon()) )

	def getCatalog(self, resultsList):
		resultsList.push_back( launchy.CatItem( "PyGoogleTranslate", "qe", self.getID(), self.getIcon() ) )

	def launchItem(self, inputDataList, catItemOrig):
		pass
		
	def hasDialog(self):
		return True
		
	def doDialog(self, parentWidgetPtr):
		parentWidget = wrapinstance(parentWidgetPtr, QtGui.QWidget)
		
		self.widget = PyGTGui.PyGTUi(parentWidget)
		self.widget.show()
			
		return unwrapinstance(self.widget)
		
	def endDialog(self, accept):
		self.widget.hide()
		if accept:
			self.widget.writeSettings()
			self.__readConfig()
		
		del self.widget
		self.widget = None
		
	def __readConfig(self):
		settings = launchy.settings
		
		# Test if the settings file has PyGT configuration
		version = settings.value("PyGT/version", QVariant("0.0")).toString()
		print_debug("PyGT version: " + version)
		if version == "0.0":
			settings.setValue("PyGT/langs/value", QVariant("||||||||||||||en|||||||||||||||||||||||||||||ru||||||||||||||"))
		
		# Set our version
		settings.setValue("PyGT/version", QVariant(self.__version__))
		
		# Read directories from the settings file
		self._languages = unicode(settings.value("PyGT/langs/value").toString())
		
launchy.registerPlugin(PyGoogleTranslate)